package ru.ifmo.network.skype.audio.send;

import ru.ifmo.network.skype.audio.Config;
import ru.ifmo.network.skype.network.MessageHandler;

import javax.sound.sampled.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.util.Arrays;
import java.util.Date;

/**
 * @author avhaliullin
 */
public class AudioGrabber implements Runnable {
    private final MessageHandler messageHandler;
    private long serialId = new Date().getTime();
    private final Config config;

    private final byte[] buf;

    public AudioGrabber(MessageHandler messageHandler, Config config) {
        this.messageHandler = messageHandler;
        this.config = config;
        double k = 32 * Math.PI / config.getBufferSize();
        ByteBuffer bb = ByteBuffer.allocate(config.getBufferSize());
        ShortBuffer sb = bb.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
        buf = bb.array();
        for (int i = 0; i < buf.length / 2; i++) {
            sb.put(i, (short) (Math.sin(i * k) * Math.min(Math.abs(Short.MIN_VALUE), Short.MAX_VALUE)));
        }
    }

    public void start() {
        new Thread(this).start();
    }


    public void run() {
        try {
            final AudioFormat format = config.getAudioFormat();
            DataLine.Info info = new DataLine.Info(
                    TargetDataLine.class, format);
            final TargetDataLine line = (TargetDataLine)
                    AudioSystem.getLine(info);
            line.open(format, config.getBufferSize() * 2);
            line.start();
            byte[] buffer = new byte[config.getBufferSize()];
            while (!Thread.interrupted()) {
                int len = line.read(buffer, 0, buffer.length);
                if (len > 0) {
                    messageHandler.handleAudio(null, serialId++, buffer);
                } else {
                    return;
                }
            }
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        }
    }
}
